
package com.gpsnav.screen;

import net.rim.device.api.ui.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.ui.component.*;
import com.gpsnav.util.*;
import com.gpsnav.ui.*;
//import com.gpsnav.util.CoordinateConversion;
import com.gpsnav.screen.DestinationScreen;
import com.gpsnav.bo.*;
import com.gpsnav.dao.OptionsDAO;
import com.gpsnav.dao.WaypointsDAO;
import net.rim.blackberry.api.invoke.*;
//import com.gpsnav.util.LayoutGrid;
//import com.gpsnav.util.GPXHandler;

import net.rim.device.api.util.*;
import net.rim.device.api.system.*;
import net.rim.blackberry.api.browser.*;
import javax.microedition.location.*;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import java.io.IOException;
import net.rim.device.api.i18n.SimpleDateFormat;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.Vector;
import java.util.Date;
//import net.rim.device.api.xml.jaxp.XMLParser;
import net.rim.device.api.i18n.DateFormat;

public class WaypointDetailScreen extends MainScreen {

    SimpleDateFormat sdf = new SimpleDateFormat(DateFormat.DATETIME_DEFAULT);
    CustomRichTextField richTextField = new CustomRichTextField("");
    CustomLabelField gcNameLbl = new CustomLabelField("GC Name: ");
    CustomLabelField gcNameField = new CustomLabelField("",FOCUSABLE);
    CustomLabelField nameLbl = new CustomLabelField("Waypoint Name: ");
    CustomLabelField nameField = new CustomLabelField("",DrawStyle.ELLIPSIS | FOCUSABLE);
    CustomLabelField locationLbl = new CustomLabelField("Location: ");
//    CustomLabelField locationField = new CustomLabelField("",DrawStyle.ELLIPSIS | FOCUSABLE);
    CustomRichTextField locationField = new CustomRichTextField (" \n \n ", DrawStyle.ELLIPSIS | FOCUSABLE);
    CustomLabelField dateLbl = new CustomLabelField("Date: ");
    CustomRichTextField dateField = new CustomRichTextField("", DrawStyle.ELLIPSIS | FOCUSABLE);
    CustomLabelField typeLbl = new CustomLabelField("Type: ");
    CustomLabelField typeField = new CustomLabelField("",DrawStyle.ELLIPSIS);
    CustomLabelField sizeLbl = new CustomLabelField("Size: ");
    CustomLabelField sizeField = new CustomLabelField("",DrawStyle.ELLIPSIS);
    CustomLabelField difficultyLbl = new CustomLabelField("Diff: ");
    CustomLabelField difficultyField = new CustomLabelField("",DrawStyle.ELLIPSIS);
    CustomLabelField terrainLbl = new CustomLabelField("Terr: ");
    CustomLabelField terrainField = new CustomLabelField("",DrawStyle.ELLIPSIS);
    CustomLabelField descriptionLbl = new CustomLabelField("Description: ");
    CustomRichTextField descriptionField = new CustomRichTextField("",FOCUSABLE);//new CustomLabelField("", FOCUSABLE | SCROLLABLE);
    //Field descriptionField = browserContent.getDisplayableContent();
    CustomLabelField urlLbl = new CustomLabelField("URL: ");
    CustomLabelField urlField = new CustomLabelField("", FOCUSABLE);
    CustomLabelField hintLbl = new CustomLabelField("Hint: ");
    CustomLabelField hintField = new CustomLabelField("", FOCUSABLE);
    CustomLabelField nearestLbl = new CustomLabelField("Link for nearest caches: ");
    CustomLabelField nearestField = new CustomLabelField("", FOCUSABLE);
    CustomLabelField gcLbl = new CustomLabelField("GC");
    CustomLabelField gcField = new CustomLabelField("", FOCUSABLE); 
    CustomVerticalFieldManager logManager = new CustomVerticalFieldManager();
    Font fnt = (new RichTextField()).getFont().derive(Font.PLAIN, 1);
    Font fntBold = (new RichTextField()).getFont().derive(Font.BOLD, 1);

    public static Waypoint destination = null;
    Options options = new Options();
    CoordinateConversion conv = new CoordinateConversion();
    Calculation calc = new Calculation();
    private boolean blnEncrypted = true;

    public WaypointDetailScreen() {
        CustomVerticalFieldManager v = new CustomVerticalFieldManager(VERTICAL_SCROLLBAR|VERTICAL_SCROLL);
        try {
            FontFamily ff = FontFamily.forName(Options.getFontFamily());
            fnt = ff.getFont(FontFamily.TRUE_TYPE_FONT, Options.getDetailsFontSize()).derive(Font.PLAIN);
            fntBold = ff.getFont(FontFamily.TRUE_TYPE_FONT, Options.getDetailsFontSize()).derive(Font.BOLD);
        } catch(Exception e) {
        }

        nameLbl.setFont(fntBold);
        nameField.setFont(fnt);
        gcNameLbl.setFont(fntBold);
        gcNameField.setFont(fnt);
        locationLbl.setFont(fntBold);
        locationField.setFont(fnt);
        dateLbl.setFont(fntBold);
        dateField.setFont(fnt);
        typeLbl.setFont(fntBold);
        typeField.setFont(fnt);
        sizeLbl.setFont(fntBold);
        sizeField.setFont(fnt);
        difficultyLbl.setFont(fntBold);
        difficultyField.setFont(fnt);
        terrainLbl.setFont(fntBold);
        terrainField.setFont(fnt);
        descriptionLbl.setFont(fntBold);
        descriptionField.setFont(fnt);
        urlLbl.setFont(fntBold);
        urlField.setFont(fnt);
        hintLbl.setFont(fntBold);
        hintField.setFont(fnt);
        nearestLbl.setFont(fntBold);
        nearestField.setFont(fnt);
 
        LayoutGrid h = new LayoutGrid(2);
        //HorizontalFieldManager h = new HorizontalFieldManager();
        h.add(nameLbl);
        h.add(nameField);
        v.add(h);
        
        //h = new HorizontalFieldManager();
        h.add(gcNameLbl);
        h.add(gcNameField);
        //v.add(h);
        
        //h = new HorizontalFieldManager();
        h.add(locationLbl);
        h.add(locationField);
        //v.add(h);

        h.add(dateLbl);
        h.add(dateField);

        LayoutGrid g = new LayoutGrid(4);
        g.add(typeLbl);
        g.add(typeField);
        g.add(sizeLbl);
        g.add(sizeField);
        g.add(difficultyLbl);
        g.add(difficultyField);
        g.add(terrainLbl);
        g.add(terrainField);
        
        v.add(g);
        
        v.add(descriptionLbl);
        v.add(descriptionField);
        v.add(urlLbl); 
        v.add(urlField);
        v.add(new CustomLabelField(""));
        v.add(new CustomLabelField(""));
        v.add(hintLbl);
        v.add(hintField);
        v.add(nearestLbl);
        v.add(nearestField);
        add(v);
        
        add(logManager);
//
//        add(richTextField);
    }

    public MenuItem backMenuItem = new MenuItem("Back", 1,1){
        public void run(){
            UiApplication.getUiApplication().popScreen();
        }
    };

    public MenuItem getCacheMenuItem = new MenuItem("Goto Cache URL", 1,1){
        public void run(){
            if (urlField.toString() == "http://")
              {
               Dialog.inform("Not a CACHE");    
              } else {
               net.rim.blackberry.api.browser.Browser.getDefaultSession().displayPage(urlField.toString());;
              }
        }
    };
    
    
    public MenuItem decHintMenuItem = new MenuItem("Toggle Hint", 1,1){
        public void run(){
            if (blnEncrypted) {
                hintField.setText(destination.getDecryptedHint());
                blnEncrypted = false;
            }
            else {
                hintField.setText(destination.getEncryptedHint());
                blnEncrypted = true;
            }
        }
    };
    

    
    public MenuItem googleMapsMenuItem = new MenuItem("Google Maps", 200000,1){
        public void run(){
            if (destination != null) {
                int mh = CodeModuleManager.getModuleHandle("GoogleMaps");
                if (mh != 0) {
                    URLEncodedPostData uepd = new URLEncodedPostData(null, false);
                    uepd.append("action","LOCN");
                    uepd.append("a", "@latlon:"+destination.getLatitude()+","+destination.getLongitude());
                    uepd.append("zoom", "6");
                    uepd.append("title", destination.getKeyName());
                    uepd.append("description", destination.getName());
                    String[] args = { "http://gmm/x?"+uepd.toString() };
                    ApplicationDescriptor ad = CodeModuleManager.getApplicationDescriptors(mh)[0];
                    ApplicationDescriptor ad2 = new ApplicationDescriptor(ad, args);
                    try {
                        ApplicationManager.getApplicationManager().runApplication(ad2, true);        
                    } catch (Exception e) {
                        Dialog.inform("Unable to invoke Google Maps");
                    }
                }
                }
            }
    };
 
    public MenuItem bbMapsMenuItem = new MenuItem("Blackberry Maps", 200001,1){
        public void run(){
            if (destination != null) {
                int bbLat = (int) (destination.getLatitude()*100000);
                int bbLon = (int) (destination.getLongitude()*100000);
                String strLat = ""+bbLat;
                String strLon= ""+ bbLon;
                
                String document = "<location-document> <location lon='" + strLon + "' lat='" + strLat + "'" +
                                " label='"+ destination.getKeyName().replace('\'',' ') + "' "+
                                   " description='"+ destination.getName().replace('\'',' ') + "' zoom='6'/>" +
                                "</location-document>";

                try {
                    Invoke.invokeApplication(Invoke.APP_TYPE_MAPS,
                            new MapsArguments(
                            MapsArguments.ARG_LOCATION_DOCUMENT,document));
                } catch (Exception e) {
                    Dialog.inform("Unable to invoke Blackberry Maps");
                }

                }
            }
    };
 
    public MenuItem bcachingMenuItem = new MenuItem("View cache on bcaching", 400001,4){
        public void run(){ 
            if (destination.getGcNumber() != null && !destination.getGcNumber().trim().equals("")) {
                net.rim.blackberry.api.browser.Browser.getDefaultSession().displayPage("http://www.bcaching.com/m/Details.aspx?id="+destination.getGcNumber());
            }
        }
    };
    

    protected void makeMenu(Menu menu, int instance){
        if (Options.getShowGeocachingOptions() == 0  && Options.getAllowDataCharges() == 0) {
            menu.add(getCacheMenuItem);
    //        menu.add(bcachingMenuItem);
        }
        if (Options.getAllowDataCharges() == 0) {
            menu.add(googleMapsMenuItem);
            menu.add(bbMapsMenuItem);
        }
        menu.add(backMenuItem);
        menu.add(decHintMenuItem);
    }

    public void setWaypoint(Waypoint wp) {
/*            double lon, lat;
            float alt,speed;
            float direction = 0;
            float azimuth = 0;
            float bearing = 0;
            float destDistance = 0;
            StringBuffer sb = new StringBuffer();

            sb.append("Waypoint Name: " + wp.getName() + "\n");
            
            lon = wp.getLongitude();
            lat = wp.getLatitude();
//            alt = wp.getAltitude();
            switch (options.getCoordFormat()) {
                case 0: sb.append("Lat: " + calc.round(lat,5) );
                        sb.append("   Lon: " + calc.round(lon,5));
                        break;

                case 1: sb.append("Lat: ");
                        sb.append((lat < 0)? "S " : "N ");
                        String latTxt = Coordinates.convert(Math.abs(lat), Coordinates.DD_MM);
                        sb.append(latTxt.substring(0,latTxt.indexOf(":")) + " ");
                        sb.append(latTxt.substring(latTxt.indexOf(":")+1,latTxt.length()));
                        break;
                        

                        sb.append("   Lon: ");
                        sb.append((lon < 0)? "W " : "E ");
                        String lonTxt = Coordinates.convert(Math.abs(lon), Coordinates.DD_MM);
                        sb.append(lonTxt.substring(0,lonTxt.indexOf(":")) + " ");
                        sb.append(lonTxt.substring(lonTxt.indexOf(":")+1,lonTxt.length()));
                        break;
                case 2: sb.append("MGRS:      " + calc.formatMGRS(conv.latLon2MGRUTM(lat,lon)));
                        break;
            }

            sb.append("\ntype: " + wp.getType() + "   Size: " + wp.getSize() + "\n");
            sb.append("Difficulty: " + wp.getDifficulty() + "  Terrain: " + wp.getTerrain() + "\n");
            sb.append("Description: " + wp.getDescription() + "\n");
            sb.append("Short Description: " + wp.getShortDescription() + "\n");
            sb.append("Long Description: " + wp.getLongDescription() + "\n");
            sb.append("url: " + wp.getCacheUrl() + "\n");
            sb.append("\n\n\nHint: " + wp.getHint() + "\n");

            richTextField.setText(sb.toString());

*/            
            destination = wp;
            nameField.setText(wp.getName());
            gcNameField.setText(wp.getGcNumber());
            locationField.setText(Calculation.formatLocation(wp.getLatitude(), wp.getLongitude(), (float) wp.getAltitude()));
            dateField.setText(sdf.format(new Date(wp.getWptDate())));
            typeField.setText(wp.getType());
            sizeField.setText(wp.getSize());
            difficultyField.setText(wp.getDifficulty());
            terrainField.setText(wp.getTerrain());
            descriptionField.setText(wp.getDescription()+ wp.getShortDescription() + wp.getLongDescription());
            urlField.setText(wp.getCacheUrl());
            hintField.setText(wp.getEncryptedHint());
            blnEncrypted = true;
            nearestField.setText("http://www.geocaching.com/seek/nearest.aspx?lat=" + wp.getLatitude() + "&lng=" + wp.getLongitude() +"&dist=25&f=1");

            Vector logs = wp.getLogs();
            logManager.deleteAll();

            logManager.add(new CustomLabelField(""));
            CustomLabelField logsTitle = new CustomLabelField("Logs");
            logsTitle.setFont(fntBold);
            
            logManager.add(logsTitle);
            
            for (int i = 0; i< logs.size(); i++) {
                GeocachingLog log = (GeocachingLog)logs.elementAt(i);
                String logDate = log.getLogDate();
                String type = log.getType();
                String finder = log.getFinder();
                String text = log.getText();

//                CustomLabelField lf = new CustomLabelField(logDate + "  " + type + "  " + finder);
                CustomRichTextField lf = new CustomRichTextField(logDate + "  " + type + "  " + finder);
                lf.setFont(fntBold);
                logManager.add(lf);
//                lf = new CustomLabelField(text, FOCUSABLE);
                lf = new CustomRichTextField(text, FOCUSABLE);
                lf.setFont(fnt);
                logManager.add(lf);
                logManager.add(new CustomLabelField(""));
            }

        }

    protected void paintBackground(Graphics g) {
        if (Options.getNightMode()) {
            g.setBackgroundColor(Color.BLACK);
            g.setColor(Color.RED);
        } else {
            g.setBackgroundColor(Color.WHITE);
            g.setColor(Color.BLACK);
        }
        g.clear();
    }
}

